package com.spica.spicaschool.ui.replylist

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import coil.load
import com.drakeet.multitype.ItemViewDelegate
import com.kongzue.dialogx.dialogs.TipDialog
import com.spica.spicaschool.R
import com.spica.spicaschool.bean.reply.Reply
import com.spica.spicaschool.databinding.ItemReplyBinding
import com.spica.spicaschool.network.Url
import com.spica.spicaschool.utils.SpUtils
import com.spica.spicaschool.utils.TOKEN_SIGN
import com.spica.spicaschool.utils.toUid
import rxhttp.wrapper.param.RxHttp

/**
 * 评论&回复适配器
 */
class ReplyDelegate(val context: Context) : ItemViewDelegate<Reply, ReplyDelegate.ViewHolder>() {
  // 视图绑定
  class ViewHolder(val viewBinding: ItemReplyBinding) : RecyclerView.ViewHolder(viewBinding.root)

  override fun getItemId(item: Reply): Long = item.comId.toUid().toLong()

  override fun onBindViewHolder(holder: ViewHolder, item: Reply) {
    with(holder.viewBinding) {
      // 设置头像
      ivAvatar.load(item.user.uAvatar) {
        placeholder(R.drawable.default_head)
        error(R.drawable.default_head)
      }
      // 评论人
      tvUserName.text = item.user.uNickname
      // 回复内容
      tvReplyContent.text = item.comContent
      // 回复时间
      tvReplyTime.text = item.comTime
      tvLikeNum.text = "${item.comLikeNum}"


      if (item.repository == 1) {
        //赞过
        btnLike.load(R.drawable.ic_like_selected)
      } else {

        btnLike.setOnClickListener {
          //点赞

          RxHttp.postForm(Url.LIKE_ADD)
            .add("token", SpUtils.getSpValue(context = context, key = TOKEN_SIGN, defaultVal = ""))
            .add("id", item.comId)
            .add("type", 2)
            .asOkResponse()
            .subscribe(
              {
                btnLike.load(R.drawable.ic_like_selected)
                btnLike.setOnClickListener(null)//清除点击事件
              }, {
                TipDialog.show("点赞成功")
              }
            )

        }

      }


    }

  }

  override fun onCreateViewHolder(context: Context, parent: ViewGroup): ViewHolder {
    val viewBinding = ItemReplyBinding.inflate(LayoutInflater.from(context), parent, false)
    return ViewHolder(viewBinding)
  }
}
